const express = require('express');
const router = express.Router();
const atomgitService = require('../services/atomgit');

// Health check endpoint
router.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    timestamp: new Date().toISOString()
  });
});

// Handle all webhook events
router.post('/', (req, res) => {
  const event = req.headers['x-atomgit-event'];
  
  // Handle ping event
  if (event === 'ping') {
    return res.status(200).json({
      message: 'Ping received',
      hook_id: req.body.hook_id
    });
  }

  // Validate webhook payload
  if (!req.body || !req.body.repository) {
    return res.status(400).json({ error: 'Invalid webhook payload' });
  }
  
  // Route to appropriate handler based on event type
  switch(event) {
    case 'pull_requests':
      return handlePREvent(req, res);
    case 'pull_request_review_comment':
    case 'issue_comment':
      return handleCommentEvent(req, res);
    default:
      return res.status(200).json({ 
        message: 'Event received but no action taken',
        event: event 
      });
  }
});

async function handlePREvent(req, res) {
  const { action, pull_request, repository } = req.body;
  const { number: pullNumber } = pull_request;
  const {  owner, name: repo } = repository;
  const { login } =owner;
  try {
    switch (action) {
      case 'opened':
      case 'reopened':
        await handleNewPR(pullNumber, login, repo);
        break;
      case 'synchronized':
        await handlePRUpdate(pullNumber, login, repo);
        break;
      case 'reviewed':
        await handlePRReview(pullNumber, login, repo);
        break;
    }
    res.status(200).send('PR event processed');
  } catch (error) {
    console.error('Error processing PR event:', error);
    res.status(500).send('Error processing PR event');
  }
}

async function handleCommentEvent(req, res) {
  const { action, comment, pull_request, repository } = req.body;
  const { id: commentId, user } = comment;
  const { number: pullNumber } = pull_request;
  const { owner, name: repo } = repository;
  const { login } =owner;
  const { loginUser } = user;
  try {
    switch (action) {
      case 'created':
        await handleNewComment(pullNumber, commentId, login, repo, 'created');
        break;
      case 'submitted':
        await handleNewComment(pullNumber, commentId, login, repo,'submitted');
        break;
    }
    res.status(200).send('Comment event processed');
  } catch (error) {
    console.error('Error processing comment event:', error);
    res.status(500).send('Error processing comment event');
  }
}
const { body, validationResult } = require('express-validator');

// Handle PR webhook events
router.post('/pr', [
  body('action').isString(),
  body('pull_requests').isObject(),
  body('repository').isObject()
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { action, pull_requests, repository } = req.body;
  const { number: pullNumber } = pull_requests;
  const { owner, name: repo } = repository;
  const { login } = owner;
  try {
    switch (action) {
      case 'opened':
      case 'reopened':
        // Handle new PR
        await handleNewPR(pullNumber, login, repo);
        break;
      case 'synchronized':
        // Handle PR update
        await handlePRUpdate(pullNumber, login, repo);
        break;
      case 'reviewed':
        // Handle PR review
        await handlePRReview(pullNumber, login, repo);
        break;
    }
    res.status(200).send('Webhook processed');
  } catch (error) {
    console.error('Error processing PR webhook:', error);
    res.status(500).send('Error processing webhook');
  }
});

// Handle comment webhook events
router.post('/comment', [
  body('action').isString(),
  body('comment').isObject(),
  body('pull_requests').isObject(),
  body('repository').isObject()
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { action, comment, pull_requests, repository } = req.body;
  const { id: commentId } = comment;
  const { number: pullNumber } = pull_requests;
  const { owner, name: repo } = repository;
  const { login } = owner;
  try {
    switch (action) {
      case 'created':
        // Handle new comment
        await handleNewComment(pullNumber, commentId, login, repo);
        break;
      case 'edited':
        // Handle comment update
        await handleCommentUpdate(commentId, login, repo);
        break;
    }
    res.status(200).send('Webhook processed');
  } catch (error) {
    console.error('Error processing comment webhook:', error);
    res.status(500).send('Error processing webhook');
  }
});

async function handleNewPR(pullNumber, owner, repo) {
  try {
    // Get PR details
    const pr = await atomgitService.getPR(owner, repo, pullNumber);
    
    // Add welcome comment with PR details
    await atomgitService.addPRComment(
      owner,
      repo,
      pullNumber,
      `Thanks for your PR "${pr.title}"!\n\n` +
      `We've received your changes and will review them soon.\n` +
      `PR created at: ${new Date(pr.created_at).toLocaleString()}\n` +
      `Branch: ${pr.head.ref} → ${pr.base.ref}\n\n` +
      `Please make sure all CI checks pass.`
    );

    // Add label to PR
    // await atomgitService.addPRLabel(
    //   owner,
    //   repo,
    //   pullNumber,
    //   ['awaiting-review']
    // );
  } catch (error) {
    console.error('Error processing new PR:', error);
    throw error;
  }
}

async function handlePRUpdate(pullNumber, owner, repo) {
  // Get PR details and update labels if needed
  const pr = await atomgitService.getPR(owner, repo, pullNumber);
  // Add update comment
  await atomgitService.addPRComment(
    owner,
    repo,
    pullNumber,
    'PR has been updated. Please check the changes.'
  );
}

async function handlePRReview(pullNumber, owner, repo) {
  // Add review comment
  await atomgitService.addPRComment(
    owner,
    repo,
    pullNumber,
    'Your PR has been reviewed. Please address any comments.'
  );
}

async function handleNewComment(pullNumber, commentId, owner, repo, type) {
  // Get comment details
  // const comment = await atomgitService.getComment(owner, repo, commentId);
  // Add reply to comment
  const comment = type === 'created' ? 'Thanks for your comment!' : 'Thanks for your review!';
  await atomgitService.addCommentReply(
    owner,
    repo,
    commentId,
    pullNumber,
    comment
  );
}

async function handleCommentUpdate(commentId, owner, repo) {
  // Get updated comment
  const comment = await atomgitService.getComment(owner, repo, commentId);
  // Process comment update if needed
}

module.exports = router;
